package com.size.mall.order.service;


import ch.qos.logback.core.joran.action.ActionUtil;
import cn.hutool.core.map.MapUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.size.mall.mallapi.entity.OmsOrder;
import com.size.mall.mallapi.entity.OmsOrderItem;
import com.size.mall.mallapi.service.CartService;
import com.size.mall.mallapi.service.OrderService;
import com.size.mall.mq.ActiveMQUtil;
import com.size.mall.order.mapper.OmsOrderItemMapper;
import com.size.mall.order.mapper.OmsOrderMapper;
import com.size.mall.util.RedisUtil;
import org.apache.activemq.command.ActiveMQTextMessage;
import org.springframework.beans.factory.annotation.Autowired;
import redis.clients.jedis.Jedis;

import javax.jms.*;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.List;
import java.util.UUID;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    OmsOrderItemMapper orderItemMapper;
    @Autowired
    OmsOrderMapper orderMapper;

    @Autowired
    RedisUtil redisUtil;

    @Reference
    CartService cartService;

    @Autowired
    ActiveMQUtil activeMQUtil;


    @Override
    public String checkTradeCode(String memberId, String tradeCode) {
        Jedis jedis = null ;

        try {
            jedis = redisUtil.getJedis();
            String tradeKey = "user:" + memberId + ":tradeCode";


            String tradeCodeFromCache = jedis.get(tradeKey);// 使用lua脚本在发现key的同时将key删除，防止并发订单攻击
            //对比防重删令牌
            String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
            Long eval = (Long) jedis.eval(script, Collections.singletonList(tradeKey), Collections.singletonList(tradeCode));

            if (eval!=null&&eval!=0) {
                // jedis.del(tradeKey);
                return "success";
            } else {
                return "fail";
            }
        }finally {
            jedis.close();
        }
    }

    @Override
    public String genTradeCode(String memberId) {
        Jedis jedis = redisUtil.getJedis();

        String tradeKey = "user:"+memberId+":tradeCode";

        String tradeCode = UUID.randomUUID().toString();

        jedis.setex(tradeKey,60*15,tradeCode);

        jedis.close();

        return tradeCode;
    }

    @Override
    public void saveOrder(OmsOrder omsOrder) {

        System.out.println("保存订单");
        int insert = orderMapper.insert(omsOrder);
        if (insert > 0) {

            String orderId = omsOrder.getId();

            List<OmsOrderItem> omsOrderItems = omsOrder.getOmsOrderItems();


            for (OmsOrderItem orderItem : omsOrderItems) {

                orderItem.setOrderId(orderId);
                orderItemMapper.insert(orderItem);
            }


            // 删除数据库中的购物数据,并更新缓存




        }





    }

    @Override
    public OmsOrder getOrderByOrderTradeNo(String outTradeNo) {

        List<OmsOrder> orders = orderMapper.selectByMap(MapUtil.of("order_sn", outTradeNo));
        if (orders != null) {
            return orders.get(0);
        }
        return new OmsOrder();
    }


    @Override
    public void updateOrder(OmsOrder omsOrder) {
        QueryWrapper<OmsOrder> qw = new QueryWrapper<>();

        qw.eq("orderSn", omsOrder.getOrderSn());

        OmsOrder omsOrderUpdate = new OmsOrder();

        omsOrderUpdate.setStatus(1);

        // 发送一个订单已支付的队列，提供给库存消费
        Connection connection = null;
        Session session = null;
        try{
            connection = activeMQUtil.getConnectionFactory().createConnection();
            session = connection.createSession(true, Session.SESSION_TRANSACTED);
            Queue payhment_success_queue = session.createQueue("ORDER_PAY_QUEUE");
            MessageProducer producer = session.createProducer(payhment_success_queue);
            TextMessage textMessage=new ActiveMQTextMessage();//字符串文本
            //MapMessage mapMessage = new ActiveMQMapMessage();// hash结构

            // 查询订单的对象，转化成json字符串，存入ORDER_PAY_QUEUE的消息队列

            OmsOrder omsOrderResponse = orderMapper.selectOne(qw);


            List<OmsOrderItem> select = orderItemMapper.selectByMap(MapUtil.of("order_sn",omsOrder.getOrderSn()));
            omsOrderResponse.setOmsOrderItems(select);
            textMessage.setText(JSON.toJSONString(omsOrderResponse));

            orderMapper.update(omsOrder, qw);
            producer.send(textMessage);
            session.commit();
        }catch (Exception ex){
            // 消息回滚
            try {
                session.rollback();
            } catch (JMSException e1) {
                e1.printStackTrace();
            }
        }finally {
            try {
                connection.close();
            } catch (JMSException e1) {
                e1.printStackTrace();
            }
        }

    }



}
